/**
 * components: TaoFangCanvas海报生成
 * author: Guanyuwei
 * created Time: 2021-12-1
 *
 * 使用方法：
 * 组件外部传入 shareImageData 数据
 * 
 * 
 */
const app = getApp();
const { util } = app

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    shareImageData: {
      type: Object,
      value: {},
      observer(val) {
        console.log(val)
        if(JSON.parse(JSON.stringify(val)) != {}) {
          this.shareImageDataInit()
        }
      }
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    preview : '',
    systemInfo : ''
  },

  lifetimes: {
    ready(){
      console.log(wx.getSystemInfoSync().pixelRatio)
      this.ctx = wx.createCanvasContext('canvas-image', this)

    }
  },

  /**
   * 组件的方法列表
   */
  methods: {
    //获取图片信息将网络图片转化成临时本地目录
    getImageInfo(imgurl){
      return new Promise((resolve, reject)=>{
        wx.getImageInfo({
          src: imgurl,
          success (res) {
            resolve(res)
          },
          fail(err){
            reject(err)
          }
        })
      })
    },


    async shareImageDataInit(){
      if(!this.data.shareImageData) return;

      let { drawList } = this.data.shareImageData;

      for(var i=0;i<drawList.length;i++){
        if(drawList[i].type == 'image'){
          
          await this.getImageInfo(drawList[i].url).then(res => {
            drawList[i].url = res.path
          }, err => {
            console.error(`${drawList[i].url},加载该图片失败请检查是否配置在下载域名里面`)
          })
          
        }

      }

      this.startDraw(drawList);



    },

    startDraw(drawList){
      
      wx.showToast({
        title: '图片生成中...',
        icon : 'loading'
      })

      let that = this;

      for (let i in drawList) {

        console.log(`所有绘制数据${JSON.stringify(drawList[i])}`)

        switch (drawList[i].type) {
          case 'image':
            this.drawImage(drawList[i])
            break;
          case 'text':
            this.drawText(drawList[i])
            break;
          case 'shape':
            this.drawShape(drawList[i])
            break;
        }
      }

      this.ctx.draw(true,setTimeout(() => {
        wx.canvasToTempFilePath({
          canvasId: 'canvas-image',
          fileType: 'jpg',
          quality: 1,
          destWidth : that.data.shareImageData.width,
          destHeight : that.data.shareImageData.height,
          success(res) {
            that.setData({
              preview : res.tempFilePath
            })
            that.data.shareImageData = {}
            wx.hideToast()
           
          },
          fail(err){
            console.log(err)
          }
        },this)
      },500))


    },

    drawImage(imageData){

      const {url,left,top,width,height,circle = false} = imageData;

      if(circle){
        const { url, left, top, width} = imageData
        let r = parseInt(width / 2) // 半径
        this.ctx.save();
        this.ctx.beginPath();
        this.ctx.arc(r + left, width / 2 + top, r, 0, Math.PI * 2, false);
        this.ctx.clip();
        this.ctx.drawImage(url, left, top, width, width);
        this.ctx.restore();

      }else{
        //this.ctx.drawImage(url, left, top, width, height)
        //drawImage(imageResource, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)
        //this.ctx.drawImage(url, 0, 0, width, 100, left, top, width, height)

        wx.getImageInfo({
          src: url,
          success: res => {
            let  imgWidth = res.width  // 图片宽度
            let imgHeight = res.height  // 图片高度
            console.log(res)

            let dw = width / imgWidth
            let dh = height / imgHeight

            if(imgWidth > width && imgHeight > height || imgWidth < width && imgHeight < height){
              if (dw > dh) {
                this.ctx.drawImage(url, 0, (imgHeight - height / dw) / 2, imgWidth, height / dw, left, top, width, height)
              } else {
                this.ctx.drawImage(url, (imgWidth - width / dh) / 2, 0, width / dh, imgHeight, left, top, width, height)
              }
            } else {
              if(imgWidth < width){
                this.ctx.drawImage(url, 0, (imgHeight - height / dw) / 2, imgWidth, height / dw, left, top, width, height)
              }else {
                this.ctx.drawImage(url, (imgWidth - width / dh) / 2, 0, width / dh, imgHeight, left, top, width, height)
              }
            }

          }
        })
  

      }

    },

   

    drawText(textData){
     
      const { 
        fontSize = 20, 
        color = '#FFFFFF', 
        content, 
        left = 0, 
        top = 0, 
        textAlign = 'center', 
        lineHeight = 16, 
        maxLineNum = 2,
        maxWidth = 300, 
        weight ='normal' } = textData;

      let arrText = content.split('')
  
      this.ctx.setTextBaseline('top')
      this.ctx.setFontSize(fontSize)

      let line = '', _top = top, lineNum = 1, textLine = ''
      this.ctx.setFillStyle(color)
      this.ctx.setTextAlign(textAlign)
      this.ctx.font ='normal '+ weight + ' ' + fontSize + 'px ' + 'sans-serif'
      for (let i = 0; i < arrText.length; i++) {
        textLine += [arrText[i]]
        let textWidth = this.ctx.measureText(textLine).width || 0
        if (textWidth > maxWidth) {
          if (lineNum === maxLineNum) {
            if (i !== arrText.length) {
              textLine = textLine.substring(0, textLine.length - 1) + '...'
              this.ctx.fillText(textLine, left, _top, maxWidth)
              textLine = ''
              break
            }
          }
          this.ctx.fillText(textLine, left, _top, maxWidth)
          textLine = ''
          _top += lineHeight
          lineNum ++
        }
      }
      this.ctx.fillText(textLine, left, _top, maxWidth)

  
    },

    drawShape(rectData){
      const {left,top,width,height,radius = 0,backgroundColor = '#ffffff'} = rectData;

      if(rectData.radius <= 0){ //纯矩形
        this.ctx.fillStyle = backgroundColor;
        this.ctx.fillRect(left,top,width,height)
      }else{
        this.ctx.setLineDash();
        this.ctx.save(); // 保存当前已绘制，不然后面绘制的都显示不了
        this.ctx.beginPath();
        this.ctx.setFillStyle(backgroundColor);
        this.ctx.setStrokeStyle(backgroundColor);
        // 左上角
        this.ctx.arc(left + radius, top + radius, radius, Math.PI, Math.PI * 1.5);
        // 右上角
        this.ctx.arc(left + width - radius, top + radius, radius, Math.PI * 1.5, Math.PI * 2);
        // 右下角
        this.ctx.arc(left  + width - radius, top + height - radius, radius, 0, Math.PI * 0.5);
        // 左下角
        this.ctx.arc(left  + radius, top + height - radius, radius, Math.PI * 0.5, Math.PI);
        // border-left
        this.ctx.lineTo(left , top + radius);
      
        this.ctx.fill();
        this.ctx.stroke();
        this.ctx.closePath();
        // 剪切
        this.ctx.clip();
        this.ctx.restore(); // 恢复clicp的绘制区域，后面的都能绘制
  

      }
      
      
    },


    saveToAlbum(){
      let that = this;
      checkPermission('writePhotosAlbum', () => {
        wx.saveImageToPhotosAlbum({
          filePath: this.data.preview,
          success(res) {
            wx.showToast({
              title: '保存成功'
            })
            that.triggerEvent('customevent')
          }
        })
      }, '保存图片需要权限，请提供保存到相册的权限。');
    }
  }
})


const checkPermission = (type, onSuccess, content) => {
  type = 'scope.' + type;
  wx.getSetting({
    success(getRes) {
      const setting = getRes.authSetting;
      if (setting[type] === false) {

        wx.showModal({
          title: '温馨提示',
          content: '保存图片需要权限，请提供保存到相册的权限。',
          success (res) {
            if (res.confirm) {
              wx.openSetting({
                success(openRes) {
                  if (openRes.authSetting[type] === true) {
                    typeof onSuccess === 'function' && onSuccess();
                  }
                }
              });
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })

      } else if (setting[type] === true) {
        //如果已有授权直接执行对应动作
        typeof onSuccess === 'function' && onSuccess();
      } else {
        //如果未授权，直接执行对应动作，会自动查询授权
        typeof onSuccess === 'function' && onSuccess();
      }
    }
  })
}
